//
//  AppDelegate.m
//  忘不了
//
//  Created by rimi on 16/7/7.
//  Copyright © 2016年 handuan. All rights reserved.
//
#import "AppDelegate.h"
#import <AVOSCloud/AVOSCloud.h>
// 如果使用了实时通信模块，请添加以下导入语句：
#import <AVOSCloudIM/AVOSCloudIM.h>
#import "HomeViewController.h"
#import "GuideViewController.h"
#import "leftViewController.h"
#import "UMSocialQQHandler.h"
#import "UMSocial.h"
#import "RemindMeViewController.h"
#import "FinalViewController.h"
#define MainScreenWidth [UIScreen mainScreen].bounds.size.width

@interface AppDelegate ()

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [UMSocialData setAppKey:@"579332bee0f55a9db70023f5"];
    [UMSocialQQHandler setQQWithAppId:@"1105563634" appKey:@"HpbuebsvRgGkoLke" url:@"http://www.baidu.com"];
    
    
    // Override point for customization after application launch.
    [AVOSCloud setApplicationId:@"WCwUSU7AYRo4ClWRHT2jkg7t-gzGzoHsz"
                      clientKey:@"ojk9SW2L6zCItD9MJ2IDPhRT"];
    
    //跟踪统计应用的打开情况
    [AVAnalytics trackAppOpenedWithLaunchOptions:launchOptions];
    
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    [self.window makeKeyAndVisible];
    
    GuideViewController *guideVC = [[GuideViewController alloc]init];
    
    HomeViewController *home = [[HomeViewController alloc]init];
    UINavigationController *nvc = [[UINavigationController alloc]initWithRootViewController:home];
    
    leftViewController *leftVC = [[leftViewController alloc]init];
    leftVC.delegate = home;
    
    self.drawerController = [[MMDrawerController alloc] initWithCenterViewController:nvc leftDrawerViewController:leftVC rightDrawerViewController:nil];
    [self.drawerController setShowsShadow:YES]; //是否显示阴影效果
    self.drawerController.maximumLeftDrawerWidth = MainScreenWidth/2; //左边拉开的最大宽度
    [self.drawerController setOpenDrawerGestureModeMask:MMOpenDrawerGestureModeAll];
    [self.drawerController setCloseDrawerGestureModeMask:MMCloseDrawerGestureModeAll];
    
    self.window.rootViewController = self.drawerController;
    
    BOOL first = [[NSUserDefaults standardUserDefaults] boolForKey:@"F"];
    if (!first) {
        //如果是第一次进入就出现引导页面
        [self.window addSubview:guideVC.view];
        [self.window.rootViewController addChildViewController:guideVC];
    }
    
    //注册本地通知
    UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes: UIUserNotificationTypeBadge | UIUserNotificationTypeAlert | UIUserNotificationTypeSound categories:nil];
    [application registerUserNotificationSettings:settings];
    
    if (launchOptions[UIApplicationLaunchOptionsLocalNotificationKey]) {
        application.applicationIconBadgeNumber -= 1;   //清除角标
        // 跳转
        //        ApplicationViewController * applicationView = [[ApplicationViewController alloc] init];
        //        applicationView.view.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
        //        [self.window.rootViewController presentViewController:applicationView animated:YES completion:nil];
        //        self.window.rootViewController = home;
        //        [self.drawerController.navigationController pushViewController:home animated:YES];
        
    }
    
    return YES;
}

/**
 *  点击通知打开应用的时候会执行该方法
 *  应用在前台的时候,收到通知也会执行该方法
 *
 *  @param notification 通知
 */
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:notification.userInfo[@"message"] preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        RemindMeViewController *remindMeViewController = [RemindMeViewController getVC];
        remindMeViewController.userDate = notification.userInfo[@"alarmID"];
        
        FinalViewController *finalViewController = [[FinalViewController alloc]init];
        finalViewController.heading = notification.userInfo[@"message"];
        finalViewController.date = notification.userInfo[@"alarmID"];
        finalViewController.content = notification.userInfo[@"content"];
        [self.window.rootViewController presentViewController:finalViewController animated:YES completion:nil];
    }];
    
    [alertController addAction:sureAction];
    [self.window.rootViewController presentViewController:alertController animated:YES completion:nil];
    
    application.applicationIconBadgeNumber -= 1;
}

//强制app只响应竖屏
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
    return UIInterfaceOrientationMaskPortrait;
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    BOOL result = [UMSocialSnsService handleOpenURL:url];
    if (result == FALSE) {
        //调用其他SDK，例如支付宝SDK等
    }
    return result;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // 登录需要编写
    [UMSocialSnsService applicationDidBecomeActive];
    
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
    [self saveContext];
}

#pragma mark - Core Data stack

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

- (NSURL *)applicationDocumentsDirectory {
    // The directory the application uses to store the Core Data store file. This code uses a directory named "handuan.___" in the application's documents directory.
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (NSManagedObjectModel *)managedObjectModel {
    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"___" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it.
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    
    // Create the coordinator and store
    
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"___.sqlite"];
    NSError *error = nil;
    NSString *failureReason = @"There was an error creating or loading the application's saved data.";
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        // Report any error we got.
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
        dict[NSLocalizedFailureReasonErrorKey] = failureReason;
        dict[NSUnderlyingErrorKey] = error;
        error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
        // Replace this with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    
    return _persistentStoreCoordinator;
}


- (NSManagedObjectContext *)managedObjectContext {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (!coordinator) {
        return nil;
    }
    _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    return _managedObjectContext;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        NSError *error = nil;
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}

@end
